package com.onlinelearn.paymentservice.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class IdempotencyInterceptor implements HandlerInterceptor {
    private static final String IDEMPOTENCY_KEY_PREFIX = "idempotency:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String idempotencyKey = request.getHeader("X-Idempotency-Key");
        
        if (idempotencyKey == null || idempotencyKey.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return false;
        }

        String key = IDEMPOTENCY_KEY_PREFIX + idempotencyKey;
        
        // 检查是否已处理
        Boolean exists = redisTemplate.hasKey(key);
        if (Boolean.TRUE.equals(exists)) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            return false;
        }

        // 标记为已处理，5分钟后过期
        redisTemplate.opsForValue().set(key, "processed", 5, TimeUnit.MINUTES);
        return true;
    }
} 